﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;

namespace MyBlog.Utility._Filter
{
    public class CustomResourceFilterAttribute : Attribute, IResourceFilter
    {
        private readonly IMemoryCache _cache;
        public CustomResourceFilterAttribute(IMemoryCache cache)
        {
            _cache = cache;
        }
        public void OnResourceExecuted(ResourceExecutedContext context)
        {//Action方法执行完毕后再执行该方法
            string path = context.HttpContext.Request.Path;//  api/test/getcache
            string route = context.HttpContext.Request.QueryString.Value;// ?name=111
            string key = path + route;
            _cache.Set(key, context.Result);//缓存数据
        }

        public void OnResourceExecuting(ResourceExecutingContext context)
        {//Action方法执行之前就执行该方法
            string path = context.HttpContext.Request.Path;//  api/test/getcache
            string route = context.HttpContext.Request.QueryString.Value;// ?name=111
            string key = path + route;
            if (_cache.TryGetValue(key, out object value))
            {
                context.Result = value as IActionResult;//将缓存后的数据复制给上下文
                //如果执行了context.Result方法，就不会再执行Action方法和后续的OnResourceExecuted方法了
            }
        }
    }
}
